import MyTable from '@/component/common/myTable'
import TableSelects from '@/component/common/tableSelects/tableSelects'
import { Button, Flex, Form, Input, Popconfirm } from 'antd'
import { useEffect, useMemo, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useMessageApi } from '@/component/context/messageContext/message'
import { MyDrawer } from '@/component/common/myDrawer'
import { MyForm, MyFormProps } from '@/component/common/myForm'
import meetingApi from '../api/index'
export default function MeetingList() {
  const [searchParams, setSearchParams] = useState({
    pageNum: 1,
    pageSize: 20,
    name: '',
  })
  const location = useLocation()
  const navigate = useNavigate()
  const messageApi = useMessageApi()
  const [loading, setLoading] = useState<boolean>(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([])
  const [curMeetingData, setCurMeetingData] = useState<any>({
    id: '',
    name: '',
  })
  const [switchState, setSwitchState] = useState({
    isShowAdd: false,
    isShowEdit: false,
  })
  const [meetingState, setMeetingState] = useState({
    tableData: [],
    total: 0,
  })
  // 过滤器组件
  const Filter = () => {
    const tableOptions = [
      {
        render: (
          <Input
            key="name"
            placeholder="请输入面试名"
            value={searchParams.name}
            allowClear
            onChange={(e) => {
              setSearchParams((oldV) => {
                return { ...oldV, name: e.target.value }
              })
            }}
          />
        ),
      },
    ]
    return (
      <TableSelects
        options={tableOptions}
        source={searchParams}
        onSearch={() => {
          navigate({
            search: `?pageNum=${searchParams.pageNum}&pageSize=${searchParams.pageSize}&name=${searchParams.name}`,
          })
        }}
        buttonChildren={
          <Flex gap={'10px'}>
            {selectedRowKeys.length > 0 && (
              <Popconfirm
                title={`确定删除这 ${selectedRowKeys.length} 场面试吗？`}
                onConfirm={() => {
                  delMeeting(selectedRowKeys)
                }}>
                <Button>删除</Button>
              </Popconfirm>
            )}
            <Button
              onClick={() => {
                setSwitchState((oldV) => {
                  return { ...oldV, isShowAdd: true }
                })
              }}>
              添加
            </Button>
          </Flex>
        }></TableSelects>
    )
  }

  const getMeetings = (params: any) => {
    meetingApi.getMeetings(params).then((data: any) => {
      setMeetingState((oldV) => {
        return {
          ...oldV,
          tableData: data.meetings,
          total: data.total,
        }
      })
      setTimeout(() => {
        setLoading(false)
      }, 300)
    })
  }

  const delMeeting = (ids: Array<number>) => {
    meetingApi.delMeeting(ids).then((res) => {
      messageApi.success('删除成功')
      getMeetings(searchParams)
    })
  }
  // 添加面试弹窗组件
  const [addForm] = Form.useForm()
  const AddMeetingDrawer = () => {
    const addTagFormConf: MyFormProps = {
      name: 'addMeetingForm',
      form: addForm,
      conf: [
        {
          name: 'name',
          label: '名称',
          content: <Input placeholder="请输入面试名称" />,
          rules: [{ required: true }],
        },
      ],
      onValuesChange: (changedValues, allValues) => {
        setCurMeetingData({
          ...allValues,
        })
      },
    }
    const addMeeting = () => {
      let meetDate = {
        name: curMeetingData.name,
      }
      meetingApi.addMeeting(meetDate).then((data) => {
        messageApi.success(data)
        getMeetings(searchParams)
        setSwitchState((oldV) => {
          return { ...oldV, isShowAdd: false }
        })
      })
    }
    return (
      <MyDrawer
        open={switchState.isShowAdd}
        footer={
          <Flex gap={'1rem'} justify="right">
            <Button
              onClick={() =>
                setSwitchState((oldV) => {
                  return { ...oldV, isShowAdd: false }
                })
              }>
              取消
            </Button>
            <Button
              htmlType="submit"
              onClick={() => {
                addForm
                  .validateFields()
                  .then(() => {
                    addMeeting()
                  })
                  .catch((err) => {
                    messageApi.error(err.errorFields[0].errors[0])
                  })
              }}>
              确定
            </Button>
          </Flex>
        }
        onClose={() =>
          setSwitchState((oldV) => {
            return { ...oldV, isShowAdd: false }
          })
        }>
        <MyForm {...addTagFormConf}></MyForm>
      </MyDrawer>
    )
  }
  

  // 监听URL参数变化
  useEffect(() => {
    const searchParams = new URLSearchParams(location.search)
    const params = {
      pageNum: searchParams.get('pageNum')
        ? Number(searchParams.get('pageNum'))
        : 1,
      pageSize: searchParams.get('pageSize')
        ? Number(searchParams.get('pageSize'))
        : 20,
      name: searchParams.get('name') ? String(searchParams.get('name')) : '',
    }
    setSearchParams(params)
    getMeetings(params)
  }, [location.search])

  // 编辑标签弹窗组件
  const [editForm] = Form.useForm()
  const EditMeetingDrawer = () => {
    const updateMeeting = () => {
      let meetDate = {
        id: curMeetingData.id,
        name: curMeetingData.name,
      }
      meetingApi.updateMeeting(meetDate).then((data) => {
        messageApi.success(data)
        getMeetings(searchParams)
        setSwitchState((oldV) => {
          return { ...oldV, isShowEdit: false }
        })
      })
    }
    const editMeetingFormConf: MyFormProps = {
      name: 'editMeetingForm',
      form: editForm,
      conf: [
        {
          name: 'name',
          label: '名称',
          content: <Input placeholder="请输入面试名称" />,
          rules: [{ required: true }],
        },
      ],
      onValuesChange: (changedValues, allValues) => {
        setCurMeetingData((oldV: any) => {
          return {
            ...oldV,
            ...allValues,
          }
        })
      },
    }
    return (
      <MyDrawer
        footer={
          <Flex gap={'1rem'} justify="right">
            <Button
              onClick={() => {
                setSwitchState((oldV) => {
                  return { ...oldV, isShowEdit: false }
                })
              }}>
              取消
            </Button>
            <Button
              htmlType="submit"
              onClick={() => {
                editForm.validateFields().then(() => {
                  updateMeeting()
                })
              }}>
              确定
            </Button>
          </Flex>
        }
        open={switchState.isShowEdit}
        onClose={() =>
          setSwitchState((oldV) => {
            return { ...oldV, isShowEdit: false }
          })
        }>
        <MyForm {...editMeetingFormConf}></MyForm>
      </MyDrawer>
    )
  }



  // 表格组件
  const Table = useMemo(() => {
    const rowSelection = {
      onChange: (selectedRowKeys: any) => {
        setSelectedRowKeys(selectedRowKeys)
      },
      getCheckboxProps: (record: any) => ({
        disabled: false,
      }),
    }
    const columns: any = [
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        align: 'center',
        render: (_text: any, record: any) => {
          return (
            <Button
              variant="text"
              onClick={() => {
                navigate('/home/meeting/conf/' + record.id)
              }}>
              配置
            </Button>
          )
        },
      },
    ]
    return (
      <MyTable
        loading={loading}
        rowSelection={rowSelection}
        rowKey={(record) => record.id}
        dataSource={meetingState?.tableData}
        columns={columns}
        pageSize={searchParams.pageSize}
        total={meetingState.total}
        onPaginationChange={(pageNum, pageSize) => {
          navigate({
            search: `?pageNum=${pageNum}&pageSize=${pageSize}`,
          })
        }}
        onRow={(record) => ({
          onClick: () => {
            editForm.setFieldsValue({ ...record })
            setCurMeetingData({ ...record })
            setSwitchState((oldV) => {
              return { ...oldV, isShowEdit: true }
            })
          },
        })}></MyTable>
    )
  }, [
    loading,
    meetingState?.tableData,
    meetingState.total,
    searchParams.pageSize,
    navigate,
    editForm,
  ])

  return (
    <>
      {Filter()}
      {Table}
      {AddMeetingDrawer()}
      {EditMeetingDrawer()}
    </>
  )
}
